package com.sneakxy.mybatis.commons.orm.generation;

import com.sneakxy.mybatis.commons.dialect.Dialect;
import com.sneakxy.mybatis.commons.orm.MybatisEntityManager;

/**
 * 策略管理
 * @author 潜行的青衣
 */
public class GenerationManager {

	//ID生成策略
	private GeneratedValue generatedValue;
	
	private GenerationType generationType;
	
	private MybatisEntityManager entityManager;
	
	/**
	 * 数据库方言
	 */
	private Dialect dialect;
	
	public GenerationManager(MybatisEntityManager entityManager) {
		this.entityManager = entityManager;
		this.generatedValue = entityManager.getEntityInformation().getGeneratedValue();
		this.generationType = generatedValue != null ? generatedValue.strategy() : GenerationType.MANUAL;
		this.dialect = this.getEntityManager().getConfiguration().getDialect();
	}
	
	public GenerationType getGenerationType() {
		return generationType;
	}

	public GeneratedValue getGeneratedValue() {
		return generatedValue;
	}
	
	public MybatisEntityManager getEntityManager() {
		return entityManager;
	}

	public boolean hasIdStrategy() {
		//只有序列形式需要处理
		boolean isSequence = this.getEntityManager().getGenerationManager().getGenerationType() == GenerationType.SEQUENCE;
		//非复合主键
		boolean isNotComposite = !this.getEntityManager().getEntityInformation().isComposite();
		//是否存在主键生成策略
		return isSequence && isNotComposite;
	}
	
	public boolean needSequenceIdColumnSql() {
		return dialect.needSequenceIdColumnSql();
	}
	
	public String formatColumnName(String columnName) {
		return dialect.formatColumnName(columnName);
	}
	
	public String getSequenceIdColumnValue() {
		return dialect.getSequenceIdColumnValue(this.getGeneratedValue().generator());
	}
	
	public String getSequenceIdSql(String idColumn) {
		return dialect.getSequenceIdSql(this.getGeneratedValue().generator(), idColumn);
	}
	
}
